package dao

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"reflect"
	"reggie/bean"
	"reggie/common"
	"strings"
	"time"
)

func EmployeeDaoFind(username string) (bean.Employee, error) {

	var employee bean.Employee

	find := common.Db.Find(&employee, "username=?", username)

	if find != nil {
		return employee, find.Error
	}

	return employee, nil
}

// EmployeeDaoFindByConditions 根据条件查询 employee表格
func EmployeeDaoFindByConditions(conditions map[string]interface{}) (bean.Employee, error) {
	var employee bean.Employee
	res := common.Db.Where(conditions).Find(&employee)
	if res.Error != nil {
		return employee, res.Error
	}
	return employee, nil
}

// 根据条件更新数据库
func EmployeeDaoUpdateByConditions(emp bean.Employee) error {

	// 反射
	elem := reflect.ValueOf(&emp).Elem()
	relType := elem.Type()
	//fmt.Println("relType.NumField() = ", relType.NumField())
	m := make(map[string]interface{})
	for i := 0; i < relType.NumField(); i++ {
		if elem.Field(i).Interface() == "" || elem.Field(i).Interface() == nil {
			continue
		}
		m[relType.Field(i).Name] = elem.Field(i).Interface()
	}

	m["UpdateTime"] = strings.Split(time.Time.String(time.Now()), ".")[0]
	m["UpdateUser"] = common.GetBaseContext()
	//fmt.Println("m = ", m)

	// 根据json数据使用模板进行更新操作，默认使用的是用户id进行查找
	// 获得模板
	var employee bean.Employee
	updates := common.Db.Model(&employee).Updates(m)
	fmt.Println("updates = ", updates)
	if updates.Error != nil {
		fmt.Println("updates error = ", updates.Error)
		return updates.Error
	}

	return nil
}

func EmployeeDaoPage(page, pageSize int, name string) ([]bean.Employee, error) {

	var employeeList []bean.Employee

	find := common.Db.Limit(pageSize).Offset(page).Where("name like ?", "%"+name+"%").Find(&employeeList)

	if find != nil {
		return employeeList, find.Error
	}

	return employeeList, nil
}

func EmployeeDaoTotal(name string) (int, error) {
	//var employee bean.Employee
	var total int
	var err *gorm.DB
	if name == "" || len(name) == 0 {
		err = common.Db.Table("employee").Count(&total)
	} else {
		err = common.Db.Table("employee").Where("name like ?", "%"+name+"%").Count(&total)
	}

	//fmt.Println("err == ", err)
	//fmt.Println("total == ", total)
	if err.Error != nil {
		return 0, err.Error
	}
	return total, nil
}
